package com.yi.mall.cart.service.Impl;

import com.yi.mall.cart.mapper.CartMapper;
import com.yi.mall.common.model.Cart;
import com.yi.mall.cart.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class CartServiceImpl implements ICartService {
        @Autowired
        private CartMapper cartMapper;
    @Override
    public void add(Cart cart) {
        //购物车已经存在这个商品，则更新数量，获取该商品数量，将商品数量相加，删除旧商品，保存新商品
        if(cartMapper.existsById(cart.get_id())){
            Cart obj=cartMapper.findById(cart.get_id()).get();
            cart.setNum(obj.getNum()+cart.getNum());
            cartMapper.deleteById(cart.get_id());
        }
        cartMapper.save(cart);
    }

        @Override
        public List<Cart> list(String userId) {
            //查询条件
            Cart cart = new Cart();
            cart.setUserId(userId);
            return cartMapper.findAll(Example.of(cart), Sort.by(Sort.Direction.DESC,"createTime"));
        }

        @Override
        public void removeById(String id) {
            cartMapper.deleteById(id);
        }

    @Override
    public void removeAllById(List<String> ids) {
        cartMapper.deleteAllById(ids);
    }

    @Override
    public Cart getById(String id) {
        return cartMapper.findById(id).get();
    }
}
//jdbc:mysql://192.168.120.130:3306/shop_goods?useUnicode=true&characterEncoding=utf-8&useSSl=false&serverTimezone=Asia/Shanghai&allowPublicRetrieval=true&useSSL=true
